//
//  CHSAudioPlayer.m
//  ChildHoodStemp
//
//  Created by 日东 罗 on 13-11-11.
//
//

#import "CHSAudioPlayer.h"
#import "MicroDef.h"
#import "VoiceConverter.h"
#import "NSString+File.h"


static CHSAudioPlayer *sharedInstance = nil;

@interface CHSAudioPlayer ()<AVAudioPlayerDelegate>
{
    
}
@end

@implementation CHSAudioPlayer
@synthesize audioPlayer = _audioPlayer;

+(CHSAudioPlayer *)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        if (!sharedInstance) {
            sharedInstance = [[CHSAudioPlayer alloc] init];
        }
    });
    return sharedInstance;
}

#if !__has_feature(objc_arc)
- (id)retain { return _instance; }
- (id)autorelease { return _instance; }
- (oneway void)release {}
- (NSUInteger)retainCount { return UINT_MAX;}
#endif

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [super allocWithZone:zone];
    });
    
    return sharedInstance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return sharedInstance;
}


-(id) init
{
    self = [super init];
    if (self) {
        
        
    }
    return self;
}

-(BOOL)playSoundWithURL:(NSString *)path childMessage:(ChildHoodMessage *)childMessage
{
    if (self.childMessage == nil) {
        self.childMessage = childMessage;
        
    } else {
        if (_childMessage == childMessage) {
            
            if (self.childMessage.isPlayed == MessageSoundPlaying) {
                [self stopSound];
                return NO;
            }
        }
        
    }
    [self stopSound];
    //初始化播放器的时候如下设置
    UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
                            sizeof(sessionCategory),
                            &sessionCategory);
    
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                             sizeof (audioRouteOverride),
                             &audioRouteOverride);
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //默认情况下扬声器播放
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    
    NSError *playerError;
    NSData *wavData = [NSData dataWithContentsOfFile:path];
    if (wavData == nil) {
        return NO;
    }
    NSData *wavData1 = [VoiceConverter amrToWav:wavData];
    if (wavData1 != nil) {
        wavData = wavData1;
    }
    
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:wavData error:&playerError];
    childMessage.isPlayed = MessageSoundPlaying;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chsaudioPlayerPlayVoice" object:childMessage userInfo:nil];
    self.childMessage = childMessage;
    self.audioPlayer = player;
    _audioPlayer.delegate = self;
    [_audioPlayer play];
    return YES;
}

#pragma mark - 监听听筒or扬声器
- (void) handleNotification:(BOOL)state
{
    //    [[UIDevice currentDevice] setProximityMonitoringEnabled:state]; //建议在播放之前设置yes，播放结束设置NO，这个功能是开启红外感应
    //
    //    // bug 6071 fixed by 荣则兵 begin
    //    if(state)//添加监听
    //    {
    //        [self sensorStateChange];
    //    }
    ////        [[NSNotificationCenter defaultCenter] addObserver:self
    ////                                                 selector:@selector(sensorStateChange:) name:@"UIDeviceProximityStateDidChangeNotification"
    ////                                                   object:nil];
    //    else//移除监听
    //    {
    //        [self sensorStateChange];
    //
    //    }
    // bug 6071 fixed by 荣则兵 end
    //        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
}

//处理监听触发事件
-(void)sensorStateChange
{
    
    
    //如果此时手机靠近面部放在耳朵旁，那么声音将通过听筒输出，并将屏幕变暗（省电啊）
    //    if ([[UIDevice currentDevice] proximityState] == YES)
    //    {
    ////        NSLog(@"Device is close to user");
    //        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
    //        AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
    //
    //        //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    //    }
    //    else
    //    {
    ////        NSLog(@"Device is not close to user");
    //        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    //        AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
    //
    //        //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    //    }
}

-(BOOL) stopSound
{
    if (self.childMessage == nil) {
        return NO;
    }
    self.childMessage.isPlayed = MessageSoundPlayed;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chsaudioPlayerPlayVoice" object:self.childMessage userInfo:nil];
    [self.audioPlayer stop];
    
    return NO;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    self.childMessage.isPlayed = MessageSoundPlayed;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chsaudioPlayerPlayVoice" object:self.childMessage userInfo:nil];
}

- (BOOL)hasHeadset
{
#if TARGET_IPHONE_SIMULATOR
    //#warning *** Simulator mode: audio session code works only on a device
    return NO;
#else
    CFStringRef route;
    UInt32 propertySize = sizeof(CFStringRef);
    AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &route);
    
    if((route == NULL) || (CFStringGetLength(route) == 0)){
        // Silent Mode
        //        NSLog(@"AudioRoute: SILENT, do nothing!");
    } else {
        NSString* routeStr = (__bridge NSString*)route;
        //        NSLog(@"AudioRoute: %@", routeStr);
        
        /* Known values of route:
         * "Headset"
         * "Headphone"
         * "Speaker"
         * "SpeakerAndMicrophone"
         * "HeadphonesAndMicrophone"
         * "HeadsetInOut"
         * "ReceiverAndMicrophone"
         * "Lineout"
         */
        
        NSRange headphoneRange = [routeStr rangeOfString : @"Headphone"];
        NSRange headsetRange = [routeStr rangeOfString : @"Headset"];
        if (headphoneRange.location != NSNotFound) {
            return YES;
        } else if(headsetRange.location != NSNotFound) {
            return YES;
        }
    }
    return NO;
#endif
    
}

@end
